
package com.example.mydesignmodule.observer;

import android.util.SparseArray;

import org.json.JSONObject;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author tgw
 * @date 2021/1/22
 */
public class MySubject<T> extends Subject<T> {

    //被观察者
    private T observber;

    private LinkedHashMap<String,Observer> observerSparseArray;

    public MySubject() {
        this.observerSparseArray = new LinkedHashMap<String,Observer>();
    }

    public T getObservber() {
        return observber;
    }

    public void setObservber(T observber) {
        this.observber = observber;
    }

    public void addObserver(Observer observer, String className) {
        if (observerSparseArray.get(className) == null) {
            observerSparseArray.put(className, observer);
        }
    }

    public void update(String className) {
        if (observerSparseArray.get(className) != null) {
            Observer observer = observerSparseArray.get(className);
            observer.update();
        }
    }

    public void notifyAllObserver() {
        Iterator iterator = observerSparseArray.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            Object key = entry.getKey();
            Observer observer = (Observer) entry.getValue();
            observer.update();
        }
    }


}
